﻿/*-----------------------------------------------------------------------------------------
   Author               Date            Description
   ----------------------------------------------------------------------------------------
   Steven Applegate     01/30/2011      Initial creation
 ----------------------------------------------------------------------------------------*/

using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web.Mvc;

namespace NCPA.Common
{
    public static class QueryExtension
    {
        /// <summary>
        /// Author: Steven Applegate (01/30/2011)
        /// Description: Returns a queryable collection as a SelectList
        /// </summary>
        public static SelectList ToSelectList<T>(this IQueryable<T> query, string dataValueField, string dataTextField, object selectedValue)
        {
            return new SelectList(query, dataValueField, dataTextField, selectedValue ?? -1);
        }



        /// <summary>
        /// Author: Steven Applegate (01/30/2011)
        /// Description: Returns a queryable collection as a data table
        /// </summary>
        public static DataTable ToDataTable<T>(this IQueryable<T> data)
        {
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
            var table = new DataTable();

            for (int i = 0; i < props.Count; i++)
            {
                PropertyDescriptor prop = props[i];
                table.Columns.Add(prop.Name);
            }

            var values = new object[props.Count];
            
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    if (props[i].GetValue(item) != null)
                        // ReSharper disable PossibleNullReferenceException
                        values[i] = props[i].GetValue(item).ToString();
                        // ReSharper restore PossibleNullReferenceException
                    else
                        values[i] = "";
                }
                table.Rows.Add(values);
            }
            
            return table;
        }
    }
}